from django.utils.deprecation import MiddlewareMixin
import logging
from django.db.models import F

from bk_framework_app.models import ApiRequestCount

logger = logging.getLogger(__name__)

CMDB_BEHAVIORS = [
    'list',
    'setlist',
    'modulelist',
    'hostlist',
    'hostdetail'
]

JOB_BEHAVIORS = [
    'backup-file',
    'search-file',
    'backup-record'
]

class RecordUserBehaviorMiddleware(MiddlewareMixin):
    def process_request(self, request):
        try:
            username = request.user.username
            api_name = request.path.split('/')[-1]
            api_category = 'CMDB' if api_name in CMDB_BEHAVIORS else 'JOB' if api_name in JOB_BEHAVIORS else 'Unknown'
            api_request_count, _ =ApiRequestCount.objects.get_or_create(api_category=api_category,
                                      api_name=api_name)
            api_request_count.request_count = F("request_count")+ 1
            api_request_count.save()
        except Exception as e:  # pylint: disable=broad-except
            logger.exception(f"Unexpected Exception when recorduserbehavior: {e}")
            pass
        return None